package net.lab1024.sa.admin.module.yitihua.service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

import lombok.extern.slf4j.Slf4j;
import net.lab1024.sa.admin.module.yitihua.Cfs119Param;
import net.lab1024.sa.admin.module.yitihua.SyncController;
import net.lab1024.sa.admin.module.yitihua.dao.Cfs119HouseDao;
import net.lab1024.sa.admin.module.yitihua.domain.entity.Cfs119House;
import net.lab1024.sa.admin.module.yitihua.domain.form.Cfs119HouseAddForm;
import net.lab1024.sa.admin.module.yitihua.domain.form.Cfs119HouseQueryForm;
import net.lab1024.sa.admin.module.yitihua.domain.form.Cfs119HouseUpdateForm;
import net.lab1024.sa.admin.module.yitihua.domain.vo.Cfs119HouseVO;
import net.lab1024.sa.base.common.util.SmartBeanUtil;
import net.lab1024.sa.base.common.util.SmartPageUtil;
import net.lab1024.sa.base.common.domain.ResponseDTO;
import net.lab1024.sa.base.common.domain.PageResult;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 一体化平台户信息 Service
 *
 * @Author cfsjiazy
 * @Date 2025-09-12 11:55:01
 * @Copyright  
 */

@Service
@Slf4j
public class Cfs119HouseService {

    @Resource
    private Cfs119HouseDao cfs119HouseDao;
    @Resource
    private Cfs119BaseService cfs119BaseService;

    /**
     * 分页查询
     */
    public PageResult<Cfs119HouseVO> queryPage(Cfs119HouseQueryForm queryForm) {
        Page<?> page = SmartPageUtil.convert2PageQuery(queryForm);
        List<Cfs119HouseVO> list = cfs119HouseDao.queryPage(page, queryForm);
        return SmartPageUtil.convert2PageResult(page, list);
    }

    /**
     * 添加
     */
    public ResponseDTO<String> add(Cfs119HouseAddForm addForm) {
        Cfs119House cfs119HouseEntity = SmartBeanUtil.copy(addForm, Cfs119House.class);
        cfs119HouseDao.insert(cfs119HouseEntity);
        return ResponseDTO.ok();
    }

    /**
     * 更新
     *
     */
    public ResponseDTO<String> update(Cfs119HouseUpdateForm updateForm) {
        Cfs119House cfs119HouseEntity = SmartBeanUtil.copy(updateForm, Cfs119House.class);
        cfs119HouseDao.updateById(cfs119HouseEntity);
        return ResponseDTO.ok();
    }

    /**
     * 批量删除
     */
    public ResponseDTO<String> batchDelete(List<String> idList) {
        if (CollectionUtils.isEmpty(idList)){
            return ResponseDTO.ok();
        }

        cfs119HouseDao.deleteBatchIds(idList);
        return ResponseDTO.ok();
    }

    /**
     * 单个删除
     */
    public ResponseDTO<String> delete(String id) {
        if (null == id){
            return ResponseDTO.ok();
        }

        cfs119HouseDao.deleteById(id);
        return ResponseDTO.ok();
    }

    public void addBatch(List<Cfs119House> list) {
        if (CollectionUtils.isEmpty(list)) {
            return;
        }
        //查询id是否再数据中
        // 1. 提取所有 id
        List<String> ids = list.stream().map(Cfs119House::getId).collect(Collectors.toList());

        // 2. 只查出存在的 id（返回 List<Long>，不是整行！）

        List<String> existIds = selectExistIdsBatch(ids);
        // 4. 拆分：存在的用于更新，不存在的用于插入
        Set<String> existIdSet = new HashSet<>(existIds);
        List<Cfs119House> toUpdate = new ArrayList<>();
        List<Cfs119House> toInsert = new ArrayList<>();

        for (Cfs119House item : list) {
            if (existIdSet.contains(item.getId())) {
                toUpdate.add(item);
            } else {
                toInsert.add(item);
            }
        }
        log.info("toUpdate size:{}", toUpdate.size());
        log.info("toInsert size:{}", toInsert.size());
        // 5. 批量更新 & 批量插入（注意：空集合时跳过，避免执行空 SQL）
        if (!toUpdate.isEmpty()) {
            for (Cfs119House cfs119House : toUpdate) {
                cfs119HouseDao.updateById(cfs119House);
            }
        }
        if (!toInsert.isEmpty()) {
            for (Cfs119House cfs119House : toInsert) {
                cfs119HouseDao.insert(cfs119House);
            }
            //cfs119HouseDao.insertBatch(toInsert);
        }
    }

    public List<String> selectExistIdsBatch(List<String> ids) {
        if (ids == null || ids.isEmpty()) {
            return new ArrayList<>();
        }

        // 每批最多 1000 个
        int batchSize = 1000;
        List<String> result = new ArrayList<>();

        for (int i = 0; i < ids.size(); i += batchSize) {
            int end = Math.min(i + batchSize, ids.size());
            List<String> subIds = ids.subList(i, end);
            List<String> batchResult = cfs119HouseDao.selectExistIds(subIds);
            result.addAll(batchResult);
        }

        return result;
    }

    public String sync(Cfs119Param params) {
        int pageSize = 10000;
        //到44页了 http://localhost:1024/yitihua/getHouseListData
        int startPage = params.getStart() != null ? params.getStart() : 1; // 起始页
        int totalFetched = 0; // 累计获取的数据总量
        while (true) {
            params.setStart(startPage);
            params.setPageSize(pageSize);
            params.setReturnTotalCount("Y");
            List<Cfs119House> list = cfs119BaseService.getDataByServiceCode(params, "XF-ZDGARQ-HOUSE-LIST", Cfs119House.class);
            int fetched = list.size();
            log.info("一体化平台--当前第{}页，获取户数据{}条", startPage, fetched);
            if (fetched > 0) {
                // 累计总数
                totalFetched += fetched;
                // 批量插入
                this.addBatch(list);
            }
            // 判断是否还有下一页
            if (fetched < pageSize) {
                // 最后一页，跳出
                break;
            }
            // 继续下一页
            startPage++;
            // 限流，避免请求过快
            log.info("一体化平台--等待2秒后继续获取");
            try {
                Thread.sleep(2000); // 限流，避免请求过快
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        log.info("一体化平台--获取户数据完成，共获取 {} 条", totalFetched);
        return "success";
    }
}
